require ('./common.js');
require ('./config.js');

require ('./mqtt_client.js');
//require ('./serialport.js');

var mosca  = require('mosca'); 
global.MqttServer = new mosca.Server({
    port:global.mqtt_client_normal_port,
    http: {
        port: global.mqtt_client_ws_port,
        bundle: true,
        static: './'
    } 
});

//监听链接
global.MqttServer.on("clientConnected", function(client) {
    console.log("客户端连接:", client.id);
});

global.MqttServer.on("clientDisconnected", function(client) {
    console.log("客户端断开连接:", client.id);
});

global.MqttServer.on("published", function(packet, client) {//当客户端有连接的时候，发布主题消息
    var topic = packet.topic;
    var msg = packet.payload.toString();
    console.log(topic + ">:" + msg);

    if(topic == 'super/machine/getmachineinfo') {
        var qtt = {}; //定义消息（可以为字符串，对象等）
        qtt.machine_id = global.machine_id;
        qtt.playerid = global.playerid;

        global.MqttServer.publish({ topic: 'super/machine/getmachineinfo/return', payload: JSON.stringify(qtt) });
    }
    else if(topic == 'super/machine/paymentcode') {
        var params = JSON.parse( msg );

        global.paymentcode = params.paymentcode;

        if(global.paymentcodetimer != null) {
            clearTimeout(global.paymentcodetimer);
            global.paymentcodetimer = null;
        }

        //1分钟后，付款码失效
        global.paymentcodetimer = setTimeout(function(){ global.paymentcode=''; },60000);
        clearTimeout(global.paymentcodetimer);
        global.paymentcodetimer = null;
    }
});

global.MqttServer.on('ready', function(){
    console.log('mqtt服务器启动成功，正在等待连接...');  
});
